/**
 * Description:一些注释<br/>
 * CreateTime:2019-04-05<br/>
 * Creater: yangpengfei360@126.com <br/>
 * @author yangpengfei
 */
package cn.cnsy123.bookwebsiteserver.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;

import cn.cnsy123.bookwebsiteserver.cache.UserCacheInfo;
import cn.cnsy123.bookwebsiteserver.constant.CacheConstant;

/**
 * Description:一些注释<br/>
 * CreateTime:2019-04-05<br/>
 * Creater: yangpengfei360@126.com <br/>
 * @author yangpengfei
 */
@WebFilter(filterName = "loginPageFilter",urlPatterns = {"/loginPage","/login"})
@Order(value = 6)
public class LoginPageFilter implements Filter {
    
    private static final Logger logger = LoggerFactory.getLogger(LoginPageFilter.class);
    private static final String HOME_PAGE = "/indexPage";
    
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        UserCacheInfo userCacheInfo = (UserCacheInfo)request.getSession().getAttribute(CacheConstant.SESSION_USER);
        if(userCacheInfo != null && "GET".equalsIgnoreCase(request.getMethod())) {
            logger.error("请求携带用户信息，将跳转到【主页】页面");
            PrintWriter writer = null;
            try {
                writer = response.getWriter();
                writer.println("<script type='text/javascript'>window.top.location.href = '"+HOME_PAGE+"?status=loginSuccess';</script>");
                writer.flush();
            }catch (Exception e) {
                logger.error("跳转页面执行出错，请求错误",e);
            }finally {
                if(writer != null) {
                    writer.close();
                }
            }
            return;
        }
        //放行
        chain.doFilter(request, response);

    }

}
